package dy.com.tcp;

import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket();
        //设置超时时间
        socket.setSoTimeout(3000);
        //获取服务器的地址（这里用本机地址和端口号）
        InetSocketAddress ipv4 = new InetSocketAddress(Inet4Address.getLocalHost(), 2000);
        //连接
        socket.connect(ipv4, 3000);
        //System.out.println(Inet4Address.getLocalHost());
        System.out.println("已经发起连接，进入后续流程");
        System.out.println("客户端信息：客户端ip:" + socket.getLocalSocketAddress() + ",客户端端口：" + socket.getLocalPort());
        System.out.println("服务器信息：服务器ip:" + socket.getInetAddress() + ",服务器端口：" + socket.getPort());
        System.out.println(socket.getRemoteSocketAddress());

        try {
            todo(socket);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socket.close();
            System.out.println("socket已关闭");

        }
    }

    private static void todo(Socket client) throws IOException {
        //键盘输入字节流
        InputStream in = System.in;
        //将字节流转换为字符流
        Reader rd = new InputStreamReader(in);
        //得到buffer
        BufferedReader input = new BufferedReader(rd);


        //得到socket输出流
        OutputStream outputStream = client.getOutputStream();
        PrintStream socketPrintStream = new PrintStream(outputStream);

        //得到socket输入流
        InputStream socketIn = client.getInputStream();
        BufferedReader socketInput = new BufferedReader(new InputStreamReader(socketIn));


        boolean flag = true;
        while (flag) {
            //从键盘读取一行
            String s = input.readLine();
            //向服务器发送
            socketPrintStream.println(s);
            //从服务器获取一行
            String echo = socketInput.readLine();

            //打印
            System.out.println(echo);
            if (echo.equals("bye")) {
                flag = false;
            }
        }
        socketPrintStream.close();
        socketInput.close();
        input.close();

    }
}
